package com.example.muasic.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;

import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bilibili.magicasakura.utils.ThemeUtils;
import com.example.muasic.R;
import com.example.muasic.adapter.MenuItemAdapter;
import com.example.muasic.adapter.MyPagerAdapter;
import com.example.muasic.dialog.CardPickerDialog;
import com.example.muasic.fragment.BitSetFragment;
import com.example.muasic.fragment.FoundFragment;
import com.example.muasic.fragment.FriendFragment;
import com.example.muasic.fragment.MyFragment;
import com.example.muasic.fragment.QuickControlsFragment;
import com.example.muasic.fragment.TimingFragment;
import com.example.muasic.fragment.VideoFragment;
import com.example.muasic.info.Info;
import com.example.muasic.permissions.PermissionHelper;
import com.example.muasic.provider.MusicSqLiteHelper;
import com.example.muasic.service.IService;
import com.example.muasic.service.MusicPlayer;
import com.example.muasic.service.MusicService;
import com.example.muasic.uitl.ThemeHelper;
import com.example.muasic.widget.CustomViewPager;
import com.mob.MobSDK;
import com.mob.ums.OperationCallback;
import com.mob.ums.User;
import com.mob.ums.gui.UMSGUI;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements CardPickerDialog.ClickListener{
    RadioGroup radioGroup;
    private int[] rbs={R.id.rb_my, R.id.rb_found, R.id.rb_friend, R.id.rb_video};
    private ImageView search;
//    private TextView top_bac;
    private ListView mLvLeftMenu;
    private ActionBar ab;
    private DrawerLayout drawerLayout;
    private long time = 0;
    private MusicPlayer.ServiceToken mToken;
    private ArrayList<MusicStateListener> mMusicListener = new ArrayList<>();
    private static IService iService;
    private ServiceConnection conn;
    private MusicSqLiteHelper musicSqLiteHelper;
    private PermissionHelper permissionHelper;
    private String TAG = "PlayMusicActivity";
    private static int NowPosition;
    private static List<String> titleList = new ArrayList<>();
    private static List<Info> musicList = new ArrayList<>();
    private static List<Info> NowmusicList = new ArrayList<>();

    public  List<String>  gettitleList(){
        return titleList;
    }
    public  int getNowPosition(){
        return NowPosition;
    }
    public  void setNowPosition(int Pos){
        NowPosition=Pos;
    }
    public  List<Info> getmusicList(){
        return musicList;
    }
    public  List<Info> getNowmusicList(){
        return NowmusicList;
    }




    @Override
    public void onCreate(Bundle savedInstanceState) {
        MobSDK.init(this);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        QuickControlsFragment.setpalying(0);

        Bundle bundle = getIntent().getExtras();
        int recode = bundle.getInt("recode");
        if(recode==1){

            OperationCallback<User> callback = new OperationCallback<>();
            UMSGUI.showLogin(callback);
        }
        radioGroup =(RadioGroup) findViewById(R.id.rg_click);
        search = (ImageView) findViewById(R.id.bar_search);
        drawerLayout = (DrawerLayout) findViewById(R.id.fd);
        mLvLeftMenu = (ListView) findViewById(R.id.id_lv_left_menu);
//        top_bac = (TextView)findViewById(R.id.top_bac);
        NowPosition=-1;

        musicSqLiteHelper = new MusicSqLiteHelper(this,"music.db",1);

        Intent intent = new Intent(this, MusicService.class);
        startService(intent);
        conn = new ServiceConnection(){
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                //6. 获取IBinder对象, 以此调用暴露的函数
                iService = (IService) service;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
        };

        //绑定服务

        bindService(intent, conn, BIND_AUTO_CREATE);
        //权限代码
        permissionHelper = new PermissionHelper(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        permissionHelper.request(new PermissionHelper.PermissionCallback() {
            @Override
            public void onPermissionGranted() {
                initListView();                                          //获取权限后扫描数据库获取信息
                Log.d(TAG, "onPermissionGranted() called");
            }

            @Override
            public void onIndividualPermissionGranted(String[] grantedPermission) {
                Log.d(TAG, "onIndividualPermissionGranted() called with: grantedPermission = [" + TextUtils.join(",", grantedPermission) + "]");
            }

            @Override
            public void onPermissionDenied() {
                Log.d(TAG, "onPermissionDenied() called");
            }

            @Override
            public void onPermissionDeniedBySystem() {
                Log.d(TAG, "onPermissionDeniedBySystem() called");
            }
        });



        final CustomViewPager viewPager = (CustomViewPager) findViewById(R.id.main_viewpager);
        CustomViewPagerAdapter fragments = new CustomViewPagerAdapter(getSupportFragmentManager());
        final MyFragment myFragment=new MyFragment();
        final FoundFragment foundFragment=new FoundFragment();
        final FriendFragment friendFragment=new FriendFragment();
        final VideoFragment videoFragment=new VideoFragment();
        fragments.addFragment(myFragment);
        fragments.addFragment(foundFragment);
        fragments.addFragment(friendFragment);
        fragments.addFragment(videoFragment);
        viewPager.setAdapter(fragments);


        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for(int i=0;i<rbs.length;i++){
                    if(rbs[i] != checkedId)
                        continue;
                    viewPager.setCurrentItem(i);
                }
            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                radioGroup.check(rbs[i]);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }

        });
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Intent intent = new Intent(MainActivity.this, netsearch.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                MainActivity.this.startActivity(intent);
            }
        });
//        top_bac.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                final Intent intent = new Intent(MainActivity.this,Personal.class);
//                MainActivity.this.startActivity(intent);
//            }
//        });
        radioGroup.check(rbs[1]);
        setToolBar();
        setUpDrawer();
    }


    private void setToolBar() {
        Toolbar toolbar =  findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        ab.setTitle("");
    }

    private void setUpDrawer() {
        LayoutInflater inflater = LayoutInflater.from(this);
        mLvLeftMenu.addHeaderView(inflater.inflate(R.layout.nav_header_main, mLvLeftMenu, false));
        mLvLeftMenu.setAdapter(new MenuItemAdapter(this));

        mLvLeftMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 1:
                        final Intent intent = new Intent(MainActivity.this,Personal.class);
                        MainActivity.this.startActivity(intent);
                        break;
                    case 2:
                        drawerLayout.closeDrawers();
                        break;
//                    case 3:
//                        CardPickerDialog dialog = new CardPickerDialog();
//                        dialog.setClickListener(MainActivity.this);
//                        dialog.show(getSupportFragmentManager(), "theme");
//                        drawerLayout.closeDrawers();
//                        break;
                    case 3:
                        TimingFragment fragment3 = new TimingFragment();
                        fragment3.show(getSupportFragmentManager(), "timing");
                        drawerLayout.closeDrawers();
                        break;
                    case 4:
                        BitSetFragment bfragment = new BitSetFragment();
                        bfragment.show(getSupportFragmentManager(), "bitset");
                        drawerLayout.closeDrawers();
                        break;
                    case 5:
                        if (MusicPlayer.isPlaying()) {
                            MusicPlayer.playOrPause();
                        }
                        unbindService();
                        finish();
                        drawerLayout.closeDrawers();
                }
            }
        });
    }

    @Override
    public void onConfirm(int currentTheme) {
        if (ThemeHelper.getTheme(MainActivity.this) != currentTheme) {
            ThemeHelper.setTheme(MainActivity.this, currentTheme);
            ThemeUtils.refreshUI(MainActivity.this, new ThemeUtils.ExtraRefreshable() {
                        @Override
                        public void refreshGlobal(Activity activity) {
                            //for global setting, just do once
                            if (Build.VERSION.SDK_INT >= 21) {
                                final MainActivity context = MainActivity.this;
                                ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(null, null, ThemeUtils.getThemeAttrColor(context, android.R.attr.colorPrimary));
                                setTaskDescription(taskDescription);
                                getWindow().setStatusBarColor(ThemeUtils.getColorById(context, R.color.theme_color_primary));
                            }
                        }

                        @Override
                        public void refreshSpecificView(View view) {
                        }
                    }
            );
        }
        changeTheme();
    }

    static class CustomViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();

        public CustomViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment) {
            mFragments.add(fragment);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case android.R.id.home: //Menu icon
                drawerLayout.openDrawer(Gravity.LEFT);
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }


    /**
     * 双击返回桌面
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - time > 1000)) {
                Toast.makeText(this, "再按一次返回桌面", Toast.LENGTH_SHORT).show();
                time = System.currentTimeMillis();
            } else {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }


//    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        List<Fragment> fragments = getSupportFragmentManager().getFragments();
//        if (fragments != null) {
//            for (Fragment fragment : fragments) {
//                if (fragment != null) {
//                    fragment.onRequestPermissionsResult(requestCode,permissions,grantResults);
//                }
//            }
//        }
//    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
//        moveTaskToBack(true);
        // System.exit(0);
        // finish();
    }



    //查找内存
    private void initListView() {
        int favorite = 0;
        musicSqLiteHelper.delete();
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        cursor.moveToFirst();
        do{
            long songId = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
            long albumId = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
            int duration = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
            String albumName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
            String albumData = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_KEY));
            String musicName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            long artistId = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
            String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            String folder = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            String lrc = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE_KEY));
            String sort = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            int islocal = 1;
            /*if(musicSqLiteHelper.searchFavMusic(songId).getFavorite()==1){
                favorite = 1;
            }else {*/
            favorite = 0;

            Info music1= new Info();
            music1.setSongId(songId);
            music1.setAlbumId(albumId);
            music1.setDuration(duration);
            music1.setAlbumName(albumName);
            music1.setAlbumData(albumData);
            music1.setMusicName(musicName);
            music1.setArtist(artist);
            music1.setArtistId(artistId);
            music1.setData(data);
            music1.setFolder(folder);
            music1.setLrc(lrc);
            music1.setSort(sort);
            music1.setIslocal(islocal);
            music1.setFavorite(favorite);
            /*if(cursor.moveToFirst()){
                musicSqLiteHelper.addRecMusic(music1);
            }*/
            musicSqLiteHelper.addMusic(music1);
            musicList.add(music1);
            NowmusicList.add(music1);
            titleList.add(musicName);
        }while(cursor.moveToNext());
        cursor.close();
    }


    // 权限代码
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissionHelper != null) {
            permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
    // 权限代码结束


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 在activity结束的时候回收资源
        iService.callDestroyMusic();
        unbindService(conn);
    }
}
